package com.example.ercmssystem2.controller;

import com.example.ercmssystem2.entity.User;
import com.example.ercmssystem2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
public class AuthController {

    private static final Logger logger = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private UserService userService;

    @GetMapping("/login")
    public String login(@RequestParam(required = false) String error, 
                       @RequestParam(required = false) String logout,
                       Model model) {
        logger.info("访问登录页面，error={}, logout={}", error, logout);
        
        if (error != null) {
            logger.warn("登录错误");
            model.addAttribute("error", "用户名或密码错误，请重试");
        }
        if (logout != null) {
            logger.info("用户已登出");
            model.addAttribute("message", "您已成功退出系统");
        }
        
        // 如果用户已登录，重定向到首页
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null && auth.isAuthenticated() && !"anonymousUser".equals(auth.getPrincipal())) {
            logger.info("用户已登录，重定向到仪表盘: {}", auth.getName());
            return "redirect:/dashboard";
        }
        
        return "login";
    }
    
    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        // 对于JWT认证，前端会通过JavaScript验证token
        // 这里只返回dashboard页面模板
        logger.info("访问仪表盘页面");
        
        return "dashboard";
    }
    
    @GetMapping("/auth/status")
    @ResponseBody
    public java.util.Map<String, Object> getAuthStatus() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        java.util.Map<String, Object> result = new java.util.HashMap<>();
        
        result.put("authenticated", auth.isAuthenticated());
        result.put("principal", auth.getPrincipal().toString());
        
        if (!"anonymousUser".equals(auth.getPrincipal())) {
            User user = userService.getCurrentUser();
            if (user != null) {
                result.put("username", user.getUsername());
                result.put("role", user.getRole());
                result.put("authenticated", true);
            } else {
                result.put("authenticated", false);
                result.put("error", "无法获取用户信息");
            }
        } else {
            result.put("authenticated", false);
        }
        
        return result;
    }
} 